home *** CD-ROM | disk | FTP | other *** search
/ Amiga Plus 1995 #2 / Amiga Plus CD - 1995 - No. 2.iso / internet / faq / englisch / graphicsfileformats-tips&trick < prev    next >
Encoding:
Text File  |  1995-04-11  |  18.2 KB  |  505 lines

  1. Posted-By: auto-faq 3.1.1.2
  2. Archive-name: graphics/fileformats-faq/part4
  3. Posting-Frequency: monthly
  4. Last-modified: 01Mar95
  5.  
  6. This FAQ (Frequently Asked Questions) list contains information on graphics
  7. file formats, including, raster, vector, metafile, Page Description Language,
  8. 3D object, animation, and multimedia formats.
  9.  
  10. This FAQ is divided into four parts, each covering a different area of
  11. graphics file format information:
  12.  
  13.   Graphics File Formats FAQ: General Graphics Format Questions (Part 1 of 4)
  14.   Graphics File Formats FAQ: Image Conversion and Display Programs (Part 2 of 4)
  15.   Graphics File Formats FAQ: Where to Get File Format Specifications (Part 3 of 4)
  16.   Graphics File Formats FAQ: Tips and Tricks of the Trade (Part 4 of 4)
  17.  
  18. Please email contributions, corrections, and suggestions about this FAQ to
  19. jdm@netcom.com. Relevant information posted to newsgroups will not
  20. automatically make it into this FAQ.
  21.  
  22. -- James D. Murray (jdm@netcom.com)  ;-{)>>>>
  23.  
  24. ----------------------------------------------------------------------
  25.  
  26. Subject: 0. Contents of Tips and Tricks of the Trade
  27.  
  28. Subjects marked with <NEW> are new to this FAQ.
  29. Subjects marked with <UPD> have been updated since the last release
  30.  of this FAQ.
  31.  
  32. I. General questions about this FAQ
  33.  
  34. 0. Maintainer's Comments
  35. 1. What's new in this latest FAQ release?
  36.  
  37. II. Programming Tips for Graphics File Formats
  38.  
  39. 0. What's the best way to read a file header?
  40. 1. What's this business about endianness? <UPD>
  41. 2. How can I determine the byte-order of a system at run-time? <NEW>
  42. 3. How can I identify the format of a graphics file?
  43.  
  44. III. Kudos and Assertions
  45.  
  46. 0. Acknowledgments 
  47. 1. About The Author 
  48. 2. Disclaimer 
  49. 3. Copyright Notice
  50.  
  51. ------------------------------
  52.  
  53. Subject: I. General questions about this FAQ
  54.  
  55. ------------------------------
  56.  
  57. Subject: 0. Maintainer's Comments
  58.  
  59. Programmer's are code-hungry people. They just want the secrets and they want
  60. them to work NOW! But always in the back of a hack's mind there are the
  61. questions: "Is this really the best way to do this? Could it be better?".
  62.  
  63. This FAQ is to share ideas on the implementation details of reading, writing,
  64. converting, and displaying graphics file formats. You'll probably get some
  65. good ideas here, find a few things you didn't know about, and even have a few
  66. suggestions and improvements of you own to add (send them to jdm@netcom.com).
  67.  
  68. If you need to know the best way to do something with file formats, or just
  69. find it embarrassing to implement a chunk of some other programmer's code and
  70. then have to admit you really don't understand how it works, then this FAQ is
  71. for you.
  72.  
  73. ------------------------------
  74.  
  75. Subject: 1. What's new in this latest FAQ release?
  76.  
  77.   o First release of this new FAQ part!
  78.  
  79. ------------------------------
  80.  
  81. Subject: II. Programming Tips for Graphics File Formats
  82.  
  83. ------------------------------
  84.  
  85. Subject: 0. What's the best way to read a file header?
  86.  
  87. You wouldn't think there's a lot of mystery about reading a few bytes from a
  88. disk file, eh? Programmer's, however, are constantly loosing time because
  89. they don't consider a few problems that may occur and cause them to loose
  90. time. Consider the following code:
  91.  
  92.   typedef struct _Header
  93.   {
  94.     BYTE Id;
  95.     WORD Height;
  96.     WORD Width;
  97.     BYTE Colors;
  98.   } HEADER;
  99.  
  100.   HEADER Header;
  101.  
  102.   void ReadHeader(FILE *fp)
  103.   {
  104.     if (fp != (FILE *)NULL)
  105.       fread(&Header, sizeof(HEADER), 1, fp);
  106.   }
  107.  
  108. Looks good, right? The fread() will read the next sizeof(HEADER) bytes from a
  109. valid FILE pointer into the Header data structure. So what could go wrong?
  110.  
  111. The problem often encountered with this method is one of element alignment
  112. within structures. Compilers may pad structures with "invisible" elements to
  113. allow each "visible" element to align on a 2- or 4-byte address boundary.
  114. This is done for efficiency in accessing the element while in memory. Padding
  115. may also be added to the end of the structure to bring it's total length to
  116. an even number of bytes. This is done so the data following the structure in
  117. memory will also align on a proper address boundary.
  118.  
  119. If the above code is compiled with no (or 1-byte) structure alignment the
  120. code will operate as expected. With 2-byte alignment an extra two bytes would
  121. be added to the HEADER structure in memory and make it appear as such:
  122.  
  123.   typedef struct _Header
  124.   {
  125.     BYTE Id;
  126.     BYTE Pad1;      // Added padding
  127.     WORD Height;
  128.     WORD Width;
  129.     BYTE Colors;
  130.     BYTE Pad2;      // Added padding
  131.   } HEADER;
  132.  
  133. As you can see the fread() will store the correct value in Id, but the first
  134. byte of Height will be stored in the padding byte. This will throw off the
  135. correct storage of data in the remaining part of the structure causing the
  136. values to be garbage.
  137.  
  138. A compiler using 4-byte alignment would change the HEADER in memory as such:
  139.  
  140.   typedef struct _Header
  141.   {
  142.     BYTE Id;
  143.     BYTE Pad1;      // Added padding
  144.     BYTE Pad2;      // Added padding
  145.     BYTE Pad3;      // Added padding
  146.     WORD Height;
  147.     WORD Width;
  148.     BYTE Colors;
  149.     BYTE Pad4;      // Added padding
  150.     BYTE Pad5;      // Added padding
  151.     BYTE Pad6;      // Added padding
  152.   } HEADER;
  153.  
  154. What started off as a 6-byte header increased to 8 and 12 bytes thanks to
  155. alignment. But what can you do? All the documentation and makefiles you write
  156. will not prevent someone from compiling with the wrong options flag and then
  157. pulling their (or your) hair out when your software appears not to work
  158. correctly.
  159.  
  160. Now considering this alternative to the ReadHeader() function:
  161.  
  162.   HEADER Header;
  163.  
  164.   void ReadHeader(FILE *fp)
  165.   {
  166.     if (fp != (FILE *)NULL)
  167.     {
  168.       fread(&Header.Id, sizeof(Header.Id), 1, fp);
  169.       fread(&Header.Height, sizeof(Header.Height), 1, fp);
  170.       fread(&Header.Width, sizeof(Header.Width), 1, fp);
  171.       fread(&Header.Colors, sizeof(Header.Colors), 1, fp);
  172.     }
  173.   }
  174.  
  175. What both you and your compiler now see is a lot more code. Rather than
  176. reading the entire structure in one, elegant shot, you read in each element
  177. separately using multiple calls to fread(). The trade-off here is increased
  178. code size for not caring what the structure alignment option of the compiler
  179. is set to. These cases are also true for writing structures to files using
  180. fwrite(). Write only the data and not the padding please.
  181.  
  182. But is there still anything we've yet over looked? Will fread() (fscanf(),
  183. fgetc(), and so forth) always return the data we expect?  Will fwrite()
  184. (fprintf(), fputc(), and so forth) ever write data that we don't want, or in
  185. a way we don't expect? Read on to the next section...
  186.  
  187. ------------------------------
  188.  
  189. Subject: 1. What's this business about endianness?
  190.  
  191. So you've been pulling you hair out trying to discover why your elegant and
  192. perfect-beyond-reproach code, running on your Macintosh or Sun, is reading
  193. garbage from PCX and TGA files. Or perhaps your MS-DOS or Windows
  194. application just can't seem to make heads or tails out of that Sun Raster
  195. file. And, to make matters even more mysterious, it seems your most
  196. illustrious creation will read some TIFF files, but not others.
  197.  
  198. As was hinted at in the previous section, just reading the header of a
  199. graphics file one field is not enough to insure data is always read correctly
  200. (not enough for portable code, anyway). In addition to structure, we must also
  201. consider the endianness of the file's data, and the endianness of the
  202. system's architecture our code is running on.
  203.  
  204. Here's are some baseline rules to follow:
  205.  
  206.   1) Graphics files typically use a fixed byte-ordering scheme. For example, 
  207.      PCX and TGA files are always little-endian; Sun Raster and Macintosh
  208.      PICT are always big-endian.
  209.   2) Graphics files that may contain data using either byte-ordering scheme
  210.      (for example TIFF) will have an identifier that indicates the
  211.      endianness of the data.
  212.   3) ASCII-based graphics files (such as DXF and most 3D object files),
  213.      have no endianness and are always read in the same way on any system.
  214.   4) Most CPUs use a fixed byte-ordering scheme. For example, the 80486
  215.      is little-endian and the 68040 is big-endian.
  216.   5) You can test for the type of endianness a system using software.
  217.   6) There are many systems that are neither big- nor little-endian; these
  218.      middle-endian systems will possibly cause such byte-order detection
  219.      tests to return erroneous results.
  220.  
  221. Now we know that using fread() on a big-endian system to read data from a
  222. file that was originally written in little-endian order will return incorrect
  223. data. Actually, the data is correct, but the bytes that make up the data are
  224. arranged in the wrong order. If we attempt to read the 16-bit value 1234h
  225. from a little-endian file, it would be stored in memory using the big-endian
  226. byte-ordering scheme and the value 3412h would result. What we need is a swap
  227. function to change the resulting position of the bytes:
  228.  
  229.   WORD SwapTwoBytes(WORD w)
  230.   {
  231.       register WORD tmp;
  232.       tmp =  (w & 0x00FF);
  233.       tmp = ((w & 0xFF00) >> 0x08) | (tmp << 0x08);
  234.       return(tmp);
  235.   }
  236.   
  237. Now we can read a two-byte header value and swap the bytes as such:
  238.  
  239.   fread(&Header.Height, sizeof(Header.Height), 1, fp);
  240.   Header.Height = SwapTwoBytes(Header.Height);
  241.  
  242. But what about four-byte values? The value 12345678h would be stored as
  243. 78563412h. What we need is a swap function to handle four-byte values:
  244.  
  245.   DWORD SwapFourBytes(DWORD dw)
  246.   {
  247.       register DWORD tmp;
  248.       tmp =  (dw & 0x000000FF);
  249.       tmp = ((dw & 0x0000FF00) >> 0x08) | (tmp << 0x08);
  250.       tmp = ((dw & 0x00FF0000) >> 0x10) | (tmp << 0x08);
  251.       tmp = ((dw & 0xFF000000) >> 0x18) | (tmp << 0x08);
  252.       return(tmp);
  253.   }
  254.  
  255. But how do we know when to swap and when not to swap? We always know the
  256. byte-order of a graphics file that we are reading, but how do we check what
  257. the endianness of system we are running on is? Using the C language, we might
  258. use preprocessor switches to cause a conditional compile based on a system
  259. definition flag:
  260.  
  261.   #define MSDOS     1
  262.   #define WINDOWS   2
  263.   #define MACINTOSH 3
  264.   #define AMIGA     4
  265.   #define SUNUNIX   5
  266.   
  267.   #define SYSTEM    MSDOS
  268.   
  269.   #if defined(SYSTEM == MSDOS)  
  270.     // Little-endian code here
  271.   #elif defined(SYSTEM == WINDOWS)  
  272.     // Little-endian code here
  273.   #elif defined(SYSTEM == MACINTOSH)  
  274.     // Big-endian code here
  275.   #elif defined(SYSTEM == AMIGA)  
  276.     // Big-endian code here
  277.   #elif defined(SYSTEM == SUNUNIX)  
  278.     // Big-endian code here
  279.   #else
  280.   #error Unknown SYSTEM definition
  281.   #endif
  282.  
  283. My reaction to the above code was *YUCK!* (and I hope yours was too!).  A
  284. snarl of fread(), fwrite(), SwapTwoBytes(), and SwapFourBytes() functions
  285. laced between preprocessor statements is hardly elegant code, although
  286. sometimes it is our best choice. Fortunately, this is not one of those times.
  287.  
  288. What we first need is a set of functions to read the data from a file using
  289. the byte-ordering scheme of the data. This effectively combines the read\write
  290. and swap operations into one set of functions. Considering the following:
  291.  
  292.   WORD GetBigWord(FILE *fp)
  293.   {
  294.       register WORD w;
  295.       w =  (WORD) (fgetc(fp) & 0xFF);
  296.       w = ((WORD) (fgetc(fp) & 0xFF)) | (w << 0x08);
  297.       return(w);
  298.   }
  299.   
  300.   WORD GetLittleWord(FILE *fp)
  301.   {
  302.       register WORD w;
  303.       w =  (WORD) (fgetc(fp) & 0xFF);
  304.       w = ((WORD) (fgetc(fp) & 0xFF) << 0x08);
  305.       return(w);
  306.   }
  307.   
  308.   DWORD GetBigDoubleWord(FILE *fp)
  309.   {
  310.       register WORD dw;
  311.       dw =  (DWORD) (fgetc(fp) & 0xFF);
  312.       dw = ((DWORD) (fgetc(fp) & 0xFF)) | (dw << 0x08);
  313.       dw = ((DWORD) (fgetc(fp) & 0xFF)) | (dw << 0x08);
  314.       dw = ((DWORD) (fgetc(fp) & 0xFF)) | (dw << 0x08);
  315.       return(dw);
  316.   }
  317.   
  318.   DWORD GetLittleDoubleWord(FILE *fp)
  319.   {
  320.       register WORD dw;
  321.       dw =  (DWORD) (fgetc(fp) & 0xFF);
  322.       dw = ((DWORD) (fgetc(fp) & 0xFF) << 0x08);
  323.       dw = ((DWORD) (fgetc(fp) & 0xFF) << 0x10);
  324.       dw = ((DWORD) (fgetc(fp) & 0xFF) << 0x18);
  325.       return(dw);
  326.   }
  327.   
  328.   void PutBigWord(WORD w, FILE *fp)
  329.   {
  330.       fputc((w >> 0x08) & 0xFF, fp);
  331.       fputc(w & 0xFF, fp);
  332.   }
  333.   
  334.   void PutLittleWord(WORD w, FILE *fp)
  335.   {
  336.       fputc(w & 0xFF, fp);
  337.       fputc((w >> 0x08) & 0xFF, fp);
  338.   }
  339.   
  340.   void PutBigDoubleWord(DWORD dw, FILE *fp)
  341.   {
  342.       fputc((dw >> 0x08) & 0xFF, fp);
  343.       fputc((dw >> 0x10) & 0xFF, fp);
  344.       fputc((dw >> 0x18) & 0xFF, fp);
  345.       fputc(dw & 0xFF, fp);
  346.   }
  347.   
  348.   void PutLittleDoubleWord(DWORD dw, FILE *fp)
  349.   {
  350.       fputc(w & 0xFF, fp);
  351.       fputc((w >> 0x08) & 0xFF, fp);
  352.       fputc((w >> 0x10) & 0xFF, fp);
  353.       fputc((w >> 0x18) & 0xFF, fp);
  354.   }
  355.  
  356. If we were reading a little-endian file on a big-endian system (or visa
  357. versa), the previous code:
  358.  
  359.   fread(&Header.Height, sizeof(Header.Height), 1, fp);
  360.   Header.Height = SwapTwoBytes(Header.Height);
  361.  
  362. Would be replaced by:
  363.   
  364.   Header.Height = GetLittleWord(fp);
  365.  
  366. The code to write the same value to a file would be changed from:
  367.  
  368.   Header.Height = SwapTwoBytes(Header.Height);
  369.   fwrite(&Header.Height, sizeof(Header.Height), 1, fp);
  370.  
  371. To the slightly more readable:
  372.  
  373.   PutLittleWord(Header.Height, fp);
  374.  
  375. Note that these functions are the same regardless of the endianness of a
  376. system. For example, the ReadLittleWord() will always read a two-byte value
  377. from a little-endian file regardless of the endianness of the system;
  378. PutBigDoubleWord() will always write a four-byte big-endian value, and so
  379. forth.
  380.  
  381. ------------------------------
  382.  
  383. Subject: 2. How can I determine the byte-order of a system at run-time?
  384.  
  385. You may wish to optimize how you read (or write) data from a graphics file
  386. based on the endianness of your system. Using the GetBigDoubleWord() function
  387. mentioned in the previous section to read big-endian data from a file on a
  388. big-endian system imposes extra overhead we don't really need (although if
  389. the actual number of read/write operations in your program is small you might
  390. not consider this overhead to be too bad).
  391.  
  392. If our code could tell what the endianness of the system was at run-time, it
  393. could choose (using function pointers) what set of read/write functions to
  394. use. Look at the following function:
  395.  
  396.   #define BIG_ENDIAN      0
  397.   #define LITTLE_ENDIAN   1
  398.  
  399.   int TestByteOrder(void)
  400.   {
  401.       short int w = 0x0001;
  402.       char *byte = (char *) &word;
  403.       return(byte[0] ? LITTLE_ENDIAN : BIG_ENDIAN);
  404.   }
  405.  
  406. This code assigns the value 0001h to a 16-bit integer. A char pointer is then
  407. assigned to point at the first (least-significant) byte of the integer value.
  408. If the first byte of the integer is 01h, then the system is little-endian
  409. (the 01h is in the lowest, or least-significant, address). If it is 00h then
  410. the system is big-endian.
  411.  
  412. ------------------------------
  413.  
  414. Subject: 3. How can I identify the format of a graphics file?
  415.  
  416. When writing any type of file or data stream reader it is very important to
  417. implement some sort of method for verifying that the input data is in the
  418. format you expect. Here are a few methods:
  419.  
  420. 1) Trust the user of your program to always supply the correct data, thereby
  421. freeing you from the tedious task of writing any type of format
  422. identification routines. Choose this method and you will provide solid proof
  423. that contradicts the popular claim that users are inherently far more stupid
  424. than programmers.
  425.  
  426. 2) Read the file extension or descriptor. A GIF file will always have the
  427. extension .GIF, right? Targa files .TGA, yes?  And TIFF files will have
  428. an extension of .TIF or a descriptor of TIFF. So no problem?
  429.  
  430. Well, for the most part, this is true. This method certainly isn't
  431. bulletproof, however.  Your reader will occasionally be fed the odd-batch of
  432. mis-label files ("I thought they were PCX files!"). Or files with
  433. unrecognized mangled extensions  (.TAR rather than .TGA or .JFI rather than
  434. .JPG) that your reader knows how to read, but won't read because it doesn't
  435. recognize the extensions. File extensions also won't usually tell you the
  436. revision of the file format you are reading (with some revisions creating an
  437. almost entirely new format). And more than one file format share the more
  438. common file extensions (such as .IMG and .PIC). And last of all, data streams
  439. have no file extensions or descriptors to read at all.
  440.  
  441. 3) Read the file and attempt to recognize the format by specific patterns in
  442. the data. Most file formats contain some sort of identifying pattern of data
  443. that is identical in all files. In some cases this pattern gives and
  444. indication of the revision of the format (such as GIF87a and GIF89a) or
  445. the endianness of the data format.
  446.  
  447. Nothing is easy, however. Not all formats contain such identifiers (such as
  448. PCX). And those that do don't necessarily put it at the beginning of the
  449. file. This means if the data is in the format of a stream you many have to
  450. read (and buffer) most or all of the data before you can determine the
  451. format. Of course, not all graphics formats are suitable to be read as a data
  452. stream anyway.
  453.  
  454. Your best bet for a method of format detection is a combination of methods
  455. two and three. First believe the file extension or descriptor, read some
  456. data, and check for identifying data patterns. If this test fails, then
  457. attempt to recognize all other known patterns.
  458.  
  459. Run-time file format identification a black-art at best.
  460.  
  461. ------------------------------
  462.  
  463. Subject: III. Kudos and Assertions
  464.  
  465. ------------------------------
  466.  
  467. Subject: 0. Acknowledgments
  468.  
  469. Nobody yet. 
  470.  
  471. Doesn't anybody have any neat tricks to share?
  472.  
  473. ------------------------------
  474.  
  475. Subject: 1. About The Author
  476.  
  477. The author of this FAQ, James D. Murray, lives in the City of Orange, Orange
  478. County, California, USA. He is the co-author of the book Encyclopedia of
  479. Graphics File Formats published by O'Reilly and Associates, makes a passable
  480. living writing Microsoft Windows applications in C++, and may be reached as
  481. jdm@netcom.com, or via U.S. Snail at: P.O. Box 70, Orange, CA 92666-0070 USA.
  482.  
  483. GCS d-- H++ s g- p? au+ a w+ v++ C+++(++++) US+++ p++>++++ L>++ 3 E--- N++ K-
  484. W---$ M-@ V-- po Y+ t++ 5-- j>x R+>-- G' tv-->! b+++ D++ B e- u* h- f r-->+++
  485. n++ y*(**)
  486.  
  487. ------------------------------
  488.  
  489. Subject: 2. Disclaimer
  490.  
  491. While every effort has been taken to insure the accuracy of the information
  492. contained in this FAQ list compilation, the author and contributors assume no
  493. responsibility for errors or omissions, or for damages resulting from the use
  494. of the information contained herein.
  495.  
  496. ------------------------------
  497.  
  498. Subject: 3. Copyright Notice
  499.  
  500. This FAQ is Copyright (C) 1994-95 by James D. Murray. All Rights Reserved. 
  501. This work may be reproduced, in whole or in part, using any medium,
  502. including, but not limited to, electronic transmission, CD-ROM, or published
  503. in print, under the condition that this copyright notice remains intact.
  504.  
  505.